<!-- src\views\stats\MachineOverview.vue -->
<template>
  <div class="machine-overview">
    <h2>机器数据概览</h2>
    <el-form :model="filters" label-width="100px" class="filter-form">
      <el-form-item label="时间范围">
        <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="用户类型">
        <el-select v-model="filters.userType" placeholder="请选择">
          <el-option label="所有" value="" />
          <el-option label="农民" value="FARMER" />
          <el-option label="管理人员" value="MANAGER" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="applyFilters">查询</el-button>
        <el-button @click="resetFilters">重置</el-button>
        <el-button type="success" @click="exportData">导出</el-button>
      </el-form-item>
    </el-form>
    <div class="charts">
      <div id="type-chart" class="chart-container"></div>
      <div id="status-chart" class="chart-container"></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import { useMachineStore } from '@/stores/machine';
import axios from '@/plugins/axios';

const machineStore = useMachineStore();
const filters = ref(machineStore.filters);
const dateRange = ref<[Date, Date] | null>(null);

const applyFilters = async () => {
  if (dateRange.value) {
    filters.value.startDate = dateRange.value[0].toISOString().split('T')[0];
    filters.value.endDate = dateRange.value[1].toISOString().split('T')[0];
  }
  machineStore.setFilters(filters.value);
  await machineStore.fetchStatistics();
  renderCharts();
};

const resetFilters = () => {
  dateRange.value = null;
  machineStore.clearFilters();
  filters.value = machineStore.filters;
  applyFilters();
};

const exportData = async () => {
  const response = await axios.get('/machine/export', {
    params: filters.value,
    responseType: 'blob',
  });
  const url = window.URL.createObjectURL(new Blob([response.data]));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', 'machine_statistics.csv');
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const renderCharts = () => {
  const typeChart = echarts.init(document.getElementById('type-chart') as HTMLElement);
  typeChart.setOption({
    title: {
      text: '机器类型分布',
      left: 'center' // 标题居中
    },
    tooltip: {},
    series: [{
      name: '类型',
      type: 'pie',
      radius: '50%',
      data: machineStore.statistics.typeDistribution.map(item => ({ name: item.name, value: item.value })),
    }],
  });

  const statusChart = echarts.init(document.getElementById('status-chart') as HTMLElement);
  statusChart.setOption({
    title: {
      text: '机器状态分布',
      left: 'center' // 标题居中
    },
    tooltip: {},
    xAxis: { type: 'category', data: machineStore.statistics.statusDistribution.map(item => item.name) },
    yAxis: { type: 'value' },
    series: [{
      name: '数量',
      type: 'bar',
      data: machineStore.statistics.statusDistribution.map(item => item.value),
    }],
  });
};

onMounted(async () => {
  await machineStore.fetchStatistics();
  renderCharts();
});
</script>

<style scoped>
.machine-overview {
  padding: 20px;
}

.filter-form {
  margin: 0px 400px 50px 400px;
}

.charts {
  display: flex;
  flex-direction: column; /* 改为垂直布局 */
  align-items: center; /* 水平居中 */
}

.chart-container {
  width: 80%; /* 设置图表宽度，可调整 */
  height: 400px;
  margin: 20px 0; /* 图表之间的上下间距 */
}
</style>